package ${projectDomain}.adapter.login;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.unswift.annotation.api.Api;
import com.unswift.annotation.api.ApiField;
import com.unswift.annotation.api.ApiMethod;
import ${projectDomain}.adapter.AutoSqlAdapter;
import ${projectDomain}.adapter.logger.LoggerLoginRecordAdapter;
import ${projectDomain}.adapter.system.SystemUserAccountAdapter;
import ${projectDomain}.adapter.system.SystemUserAdapter;
import ${projectDomain}.pojo.bo.login.login.LogingBo;
import ${projectDomain}.pojo.cho.login.TokenUserCho;
import ${projectDomain}.pojo.cho.system.config.SystemConfigCho;
import ${projectDomain}.pojo.dao.logger.login.record.LoggerLoginRecordInsertDo;
import ${projectDomain}.pojo.dao.system.user.SystemUserDataDo;
import ${projectDomain}.pojo.dao.system.user.SystemUserUpdateDo;
import ${projectDomain}.pojo.dao.system.user.account.SystemUserAccountDataDo;
import com.unswift.exception.CoreException;
import com.unswift.utils.DateUtils;
import com.unswift.utils.ExceptionUtils;
import com.unswift.utils.ObjectUtils;
import com.unswift.utils.StringUtils;

@Component
@Api(value="登录组件，提供一些数据访问和处理的封装方法，可以快速调用，实现代码的高效复用", author="unswift", date="2023-05-31", version="1.0.0")
public class LoginAdapter extends AutoSqlAdapter{

	@Autowired
	@ApiField("用户账号公共服务")
	private SystemUserAccountAdapter systemUserAccountAdapter;
	
	@Autowired
	@ApiField("用户公共服务")
	private SystemUserAdapter systemUserAdapter;
	
	@Autowired
	@ApiField("登录日志公共服务")
	private LoggerLoginRecordAdapter loggerLoginRecordAdapter;
	
	@ApiMethod(value="用户登录时验证密码", params=@ApiField("登录Bo对象"), returns=@ApiField("token用户信息"))
	public TokenUserCho validatePassword(LogingBo loginBo){
		SystemUserAccountDataDo userAccount=systemUserAccountAdapter.findByAccount(loginBo.getAccount());//查找账号
		SystemUserDataDo systemUser=null;
		try {
			ExceptionUtils.empty(userAccount, "incorrect.username.or.password");
			systemUser=systemUserAdapter.findById(userAccount.getUserId());//查找会员
			ExceptionUtils.empty(systemUser, "incorrect.username.or.password");
			ExceptionUtils.notEquals(loginBo.getPassword(), systemUser.getPassword(), "incorrect.username.or.password");//比较密码
			handleFreeze(systemUser);
			TokenUserCho user=new TokenUserCho();
			user.setId(systemUser.getId());
			user.setAccount(userAccount.getAccount());
			user.setNickname(systemUser.getNickname());
			user.setHeadSculpturePath(null);
			user.setToken(StringUtils.getUuid());
			user.setIsAdmin(systemUser.getIsAdmin());
			loggerLoginRecordAdapter.save(new LoggerLoginRecordInsertDo(loginBo.getAccount(), (byte)1, null), false);
			return user;
		} catch(CoreException e) {
			loggerLoginRecordAdapter.save(new LoggerLoginRecordInsertDo(loginBo.getAccount(), (byte)0, e.getCode()), false);
			String loginFrozenCode=cacheAdapter.findConfigValueByKey("loginFrozenCode");
			if(!e.getCode().equals(loginFrozenCode) && ObjectUtils.isNotEmpty(systemUser) && loggerLoginRecordAdapter.isFreezeAccount(loginBo.getAccount())) {
				Date date = new Date();
				SystemUserUpdateDo update=new SystemUserUpdateDo();
				update.setId(systemUser.getId());
				update.setFreezeStatus((byte)1);
				update.setFreezeTime(date);
				systemUserAdapter.update(update, false);
			}
			throw e;
		} catch (Exception e) {
			throw e;
		}
	}

	@ApiMethod(value="处理用户冻结逻辑", params = {@ApiField("登录用户")})
	private void handleFreeze(SystemUserDataDo systemUser) {
		if(ObjectUtils.isNotEmpty(systemUser.getFreezeStatus()) && systemUser.getFreezeStatus()==1) {
			Date freezeDate=systemUser.getFreezeTime();
			SystemConfigCho config=cacheAdapter.findConfigByKey("loginUserFreezeTime");
		    ExceptionUtils.empty(config, "field.empty", "登录用户冻结时间");
		    Date invalidTime=DateUtils.getDiffAddDate(freezeDate, Integer.parseInt(config.getValue()), config.getExtend01());
			if(System.currentTimeMillis() > invalidTime.getTime()) {
				SystemUserUpdateDo update=new SystemUserUpdateDo();
				update.setId(systemUser.getId());
				this.addSet(update, "freeze_status_", 0+"");
				this.addSet(update, "freeze_time_", "null");
				systemUserAdapter.updateAuto(update, false);
			}else{
				throw ExceptionUtils.message("user.frozen");
			}
		}
	}

}
